import App from './compose'
import { User } from 'src/common/storage'
import { Context } from 'src/types/middleware'
import { IRoute } from 'src/types/route'
import { NOT_LOGIN } from 'src/enums/permissionEnum'

/**
 * 重定向（使用抛出异常中断执行）
 * @date 2021-05-11
 * @param {string} path
 * @returns {any}
 */
const redirect = (path: string) => {
    throw new Error(path)
}

App.use((ctx, next) => {
    const route = ctx.props.route as IRoute
    const { isProtected, auth } = route
    const isLogin = User.getToken()
    if (!isLogin && isProtected) {
        redirect('/login')
    }

    // 已处于登录状态，但打开只有未登录才能打开的页面
    if (isLogin && auth && auth.includes(NOT_LOGIN)) {
        redirect('/')
    }

    next()
})

const middleware = (ctx: Context, next = () => {}) => App.compose()(ctx, next)

export default middleware
